﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace SharePoint2010Poll
{
    public class CacheHelper
    {
        // Do not change. This key identifies cache for Poll web part
        public const string UniqueId = "{C1C2B248-3168-47B5-8106-BF8FB507C619}";

        public static object GetFromCache(string CacheKey, CachedObjectType CacheObjectType)
        {
            if (HttpContext.Current.Cache[GetCacheId(UniqueId, CacheKey, CacheObjectType)] != null)
            {
                return HttpContext.Current.Cache[GetCacheId(UniqueId, CacheKey,CacheObjectType)];
            }
            else
            {
                return null;
            }
        }

        public static void SetInCache(string CacheKey, CachedObjectType CacheObjectType, object obj)
        {
            HttpContext.Current.Cache.Insert(GetCacheId(UniqueId, CacheKey, CacheObjectType),
                obj,
                null,
                DateTime.UtcNow.AddMinutes(30),
                Cache.NoSlidingExpiration);
        }

        public static void InvalidateCache(string CacheKey, CachedObjectType CacheObjectType)
        {
            HttpContext.Current.Cache.Remove(GetCacheId(UniqueId, CacheKey, CacheObjectType));
        }

        private static string GetCacheId(string UniqueId, string CacheKey, CachedObjectType CacheObjectType)
        {
            return string.Format("{0}_{1}_{2}", UniqueId, CacheKey, CacheObjectType.ToString());
        }        
    }
}
